<script>
import CakeForm from "../../components/cake/CakeForm.vue";
import CakeApi from "../../api/cake";

export default {
  components: {
    CakeForm,
  },
  data() {
    return {
      cake: {},
    };
  },
  methods: {
    async getCake(cakeId) {
      try {
        const api = new CakeApi();
        let res = await api.find(cakeId);
        this.cake = res.data;
        console.log(this.cake);
      } catch (err) {
        console.error(err);
        this.$myMessageBox("应用服务器访问错误！");
      }
    },
    async cakeSave() {
      if (this.cake.title && this.cake.isbn) {
        try {
          const api = new CakeApi();
          let res = await api.edit(this.cake);
          console.log(res);
          if (res.code === 200) {
            this.$myMessageBox(res.msg);
            this.$router.push({ name: "cake-list" });
          }
        } catch (err) {
          console.error(err);
          this.$myMessageBox("应用服务器访问错误！");
        }
      } else {
        this.$myMessageBox("商品信息不完整！");
      }
    },
  },
  mounted() {
    let cakeId = this.$route.params.id;
    let cake = JSON.parse(sessionStorage.getItem(`cake-${cakeId}`));
    if (cake.id === cakeId) {
      this.cake = cake;
    } else {
      this.getCake(cakeId);
    }
  },
};
</script>

<template>
  <div class="cake-edit w80">
    <div class="header">
      <h2>编辑商品</h2>
      <p>
        <a class="button" href="javascript:void(0)" @click="$goBack">返回</a>
      </p>
    </div>
    <div class="block">
      <cake-form v-model="cake" @cake-save="cakeSave"></cake-form>
    </div>
  </div>
</template>

<style scoped></style>
